package com.front.web.hotel;

import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.GPSUtil;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.haojiangboutils.MapBuild;
import com.bootdo.hotel.domain.HotelEveryDayMoney;
import com.bootdo.hotel.domain.HotelRoomType;
import com.bootdo.lvyou.domain.LvyouCity;
import com.bootdo.lvyou.domain.LvyouScenicSpot;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@RequestMapping("/f/hotelinfo/v1/")
@RestController
public class HotelInfoControllerV1 extends  HotelSupperController{


    /**
     * 得到酒店列表
     * http://127.0.0.1/f/hotelinfo/v1/gethotellist?lon=114.46353400029057&lat=36.62493730910808&pageNo=0&pageSize=5&sort=distance&b=1
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("gethotellist")
    public R getScenicSpotByDistance(
            Integer pageNo,
            Integer pageSize,
            Double lon,
            Double lat,
            String sort,
            Integer isRemen,
            String lables,
            Long  cityId,
            String name,
            HttpServletRequest request, HttpServletResponse response){
        Map query  = null;
        if(null == lon || null == lat){
            return R.error("请传入位置信息");
        }
        //如果不是测试调用  就转gps 偏移
        if(StringUtils.isEmpty(request.getParameter("b"))){
            //火星转百度09
            double[] gps =  GPSUtil.gcj02_To_Bd09(lat, lon);
            lat = gps[0];
            lon = gps[1];
        }
        if(StringUtils.isEmpty(sort)){
            sort = "distance";
        }
        if(null != pageNo && null != pageSize){
            query =  MapBuild.getInstand().setKV("pageNo",pageNo*pageSize)
                    .setKV("pageSize", pageSize)
                    .setKV("lon", lon)
                    .setKV("lat", lat)
                    .setKV("sort", sort)
                    .setKV("lables", lables)
                    .setKV("name", name)
                    .setKV("isRemen", isRemen)
                    .setKV("cityId", cityId);
        }else{
            query =  MapBuild.getInstand()
                    .setKV("lon", lon)
                    .setKV("lat", lat)
                    .setKV("sort", sort)
                    .setKV("lables", lables)
                    .setKV("isRemen", isRemen)
                    .setKV("name", name)
                    .setKV("cityId", cityId);
        }
        if(null != pageNo){
            //总记录数
            int rows= lvyouScenicSpotService.getByLonLatCount(query);
            int pageSum=(rows-1)/pageSize+1;
            if(pageNo > pageSum-1){
                return R.error("没有更多了");
            }
        }
        List<LvyouScenicSpot> l =  lvyouScenicSpotService.getByLonLat(
                query
        );
        l.stream().forEach(item ->{
            if(item.getNewMoney() == null || item.getNewMoney().doubleValue() <= 0d){
               HotelEveryDayMoney hotelEveryDayMoney  =  hotelEveryDayMoneyService.getMinMoneyByHotelId(item.getId(),null);
               if(null != hotelEveryDayMoney && null == redisUtil.get("HOTEL_MIN_MONEY"+item.getId())){
                   LvyouScenicSpot scenicSpot = lvyouScenicSpotService.get(item.getId());
                   scenicSpot.setNewMoney(new BigDecimal(hotelEveryDayMoney.getMoney()));
                   lvyouScenicSpotService.save(scenicSpot);
                   redisUtil.set("HOTEL_MIN_MONEY"+item.getId(),"OK",3600 * 6);
               }
            }
        });
        return R.ok().put("l",l);
    }



    /**
     * 得到城市列表
     * http://127.0.0.1/f/hotelinfo/v1/get_city_all
     * @return
     */
    @RequestMapping("get_city_all")
    public R getCityAll(){
      List<LvyouCity> lvyouCities =  lvyouCityService.list(MapBuild.getInstand().setKV("parentId",1));
      lvyouCities.stream().forEach(item ->{
          LvyouCity temp = new LvyouCity();
          temp.setId(item.getId());
          temp.setName(item.getName());
          item.setChildren(getAllChild(item.getId(),item.getChildren()));
          item.getChildren().add(temp);

      });
      return R.ok().put("l",lvyouCities);
    }

    public List<LvyouCity> getAllChild(Integer id,List<LvyouCity> list){
        List<LvyouCity> list1 =  lvyouCityService.list(MapBuild.getInstand().setKV("parentId",id));
        if(null != list1 && list1.size() > 0){
            for(LvyouCity item : list1){
                list.add(item);
                getAllChild(item.getId(),list);
            }
        }
        return list;
    }


    /**
     * 得到城市列表
     * http://127.0.0.1/f/hotelinfo/v1/get_money_by_hotel_id?hotelId=13&startTime=2019-10-23&endTime=2019-10-23
     * @return
     */
    @RequestMapping("get_money_by_hotel_id")
    public R getMoneyByHotelId(
            @RequestParam("hotelId") Long hotelId,
            HttpServletRequest request,
            HttpServletResponse response) throws ParseException {
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String level = request.getParameter("level");
        if(StringUtils.isEmpty(level)){
            level = "WX,";
        }
        if(StringUtils.isEmpty(startTime)){
            startTime = DateUtils.format(new Date());
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH,1);
            endTime = DateUtils.format(calendar.getTime());
        }
        LvyouScenicSpot lvyouScenicSpot =  lvyouScenicSpotService.get(hotelId);
        if(null == lvyouScenicSpot) {
            return R.error("酒店不存在");
        }
        List<HotelRoomType> hotelRoomTypes =  hotelRoomTypeService.list(MapBuild.getInstand().setKV("hotelId",hotelId));
        String finalEndTime = endTime;
        String finalStartTime = startTime;
        String finalLevel = level;

        List<Date> dateList =  DateUtils
                .getStartTimeAndEndTimeEveryDay(
                       DateUtils.pasre(startTime,DateUtils.DATE_PATTERN),
                       DateUtils.pasre(endTime,DateUtils.DATE_PATTERN));


        hotelRoomTypes.stream().forEach(item ->{
            item.setMoneyCodeList(hotelRoomMoneyCodeService.getRoomMoneyCodeByDateGroupId(item.getHotelId(),item.getId(), finalLevel, finalStartTime, finalEndTime));
            int count = hotelRoomService.count(MapBuild.getInstand().setKV("typeId",item.getId()));
            item.setStock(count);
            //查询每日库存
            int stock  =  roomTypeStockHander(item,dateList);
            item.setStock(count - stock);
        });
        int jianye = DateUtils.caculateTotalTime(startTime,endTime);
        return R.ok().put("l",hotelRoomTypes).put("jianye",(jianye-1)).put("startTime",startTime).put("endTime",endTime);
    }


    int  roomTypeStockHander(HotelRoomType hotelRoomType,List<Date> dateList){
        int  temp = 0;
        for(Date date:dateList){
            int stock =   hotelRoomDayStatusService.getRoomStockByDate(hotelRoomType.getHotelId(),hotelRoomType.getId(),DateUtils.format(date));
            if(stock >= hotelRoomType.getStock()){
                temp = stock;
                return temp;
            }else{
                if(temp < stock){
                    temp = stock;
                }
            }
        }
        return temp;
    }


}
